<?PHP

require "rb".EXT;

class Rbpage 
{
	public 
	
	$name = '',
	$content = '',
	$created = '',
	$modified = '',
	$username = '';
	
	protected $tablename = 'wikipage';
	
	function __construct()
	{
		R::setup(sprintf('%s:%s', $GLOBALS['default_database']['driver'],$GLOBALS['default_database']['database']));
	}
	
	function update()
	{
		$sql = sprintf('UPDATE %s SET content=?, modified=?, username=? WHERE name=?', $this->tablename);
		
		$params = array(
			$this->content, $this->modified, $this->username, $this->name
		);
		
		$result = R::exec($sql, $params);
		
		return $result;
	}
	
	function delete_entry($params = array())
	{
		$sql = 'DELETE FROM wikipage where name = ?';
		
		return R::exec($sql, $params);
	}
	
	function insert_entry($params = array())
	{
		$sql = 'INSERT INTO wikipage (name,content,created,modified,username) VALUES(?,?,?,?,?)';
		
		return R::exec($sql, $params);
	}
	
	function save_entry($pk = array(), $params = array())
	{
		if(sizeof($pk) > 0)
		{
			foreach($pk as $key => $val)
			{
				$sql = sprintf('SELECT name FROM %s WHERE name = ? LIMIT 1', $this->tablename);
				$result = R::getAll($sql, array($val));
			}
			
			if(sizeof($result) > 0)
			{
				$result = $this->update($params);
			}
			else
			{
				$result = $this->insert_entry($params);
			}
			
			return $result;
		}
	}
	
	function get_page($default = '')
	{
		$page = array($default);
		
		$sql = sprintf('SELECT content FROM %s WHERE name = ? LIMIT 1', $this->tablename);
		$page = R::getRow($sql, $page); 
		
		if(sizeof($page) > 0)
		{
			$content = $page['content'];
		}
		else
		{
			$content = '';
		}
		
		return $content;
	}
	
	function get_lists($name)
	{
		return R::find($this->tablename,' name LIKE ? OR content lIKE ? ', array($name, $name));
	}
	
	function get_all_list()
	{
		return R::getAll(sprintf('SELECT name FROM %s ORDER BY name',$this->tablename));
	}
}
